<template>
    <DataGrid :auto-load="autoLoad" ref="table">
        <el-table-column label="序号" prop="id" width="80" />
        <el-table-column label="属性名称" prop="displayName">
            <template #default="{ row }">
                <el-link type="primary" :underline="false" @click="onViewItem(row)">{{ row.displayName }}</el-link>
            </template>
        </el-table-column>
        <el-table-column label="标识符" prop="attributeName" />
        <el-table-column label="属性类型" prop="attributeType">
            <template #default="{ row }">
                <template v-if="modelDetail.modifierType === 'SINGLE' && row.attributeType === 'MODEL'">
                    模型属性
                </template>
                <template v-else>
                    {{ AttributeType[row.attributeType] }}
                </template>
            </template>
        </el-table-column>
        <el-table-column label="是否必填">
            <template #default="{ row }">
                {{ row.required ? '是' : '否' }}
            </template>
        </el-table-column>
        <el-table-column label="数据类型" prop="typeName">
            <template #default="{ row }">
                {{ attributeTypeList?.[row.typeName]?.displayName || 'N/A' }}
            </template>
        </el-table-column>
        <el-table-column label="操作" width="200px">
            <template #default="{ row }">
                <el-button type="primary" link @click="onEditItem(row)">修改</el-button>
                <el-button
                    type="danger"
                    link
                    @click="onDeleteItem(row)"
                    v-if="
                        (modelDetail.modifierType === 'ABSTRACT' ||
                            row.attributeType === 'CHILD_MODEL' ||
                            modelDetail.modifierType === 'SINGLE') &&
                        row.attributeType !== 'SYSTEM' &&
                        modelDetail.activeState !== 'ACTIVATED'
                    "
                    >删除
                </el-button>

                <el-button
                    type="danger"
                    link
                    @click="onRemoveItem(row)"
                    v-if="
                        modelDetail.modifierType !== 'ABSTRACT' &&
                        modelDetail.modifierType !== 'SINGLE' &&
                        row.attributeType !== 'CHILD_MODEL' &&
                        row.attributeType !== 'SYSTEM'
                    "
                    >移除
                </el-button>
            </template>
        </el-table-column>

        <template #toolbar-search>
            <el-form :model="queryData" inline class="compact">
                <el-form-item>
                    <el-input v-model="queryData.attributeName" placeholder="属性名称/标识符" clearable />
                </el-form-item>
                <el-form-item>
                    <el-select v-model="queryData.attributeType" placeholder="属性类型" clearable>
                        <el-option v-for="(value, key) in AttributeType" :label="value" :key="key" :value="key" />
                    </el-select>
                </el-form-item>
            </el-form>
        </template>

        <template #toolbar-operation>
            <el-button type="primary" @click="onNewItem">新建</el-button>
            <el-button type="primary" @click="onSelectFormParent" v-if="modelDetail.modifierType === 'EXTENDED'">
                从父模型选择
            </el-button>
        </template>
    </DataGrid>
</template>
<script setup lang="ts">
import type { AutoLoadConfig, DataGridInstance } from '@great/components';
import { DataGrid } from '@great/components';
import { modelService } from '@great/services';
import { AttributeType } from '@/utils/constant.ts';
import { showPopupBox } from '@great/utils';
import AttributeFormModal from '@/pages/model/thing/components/detail/thingModel/components/AttributeFormModal.vue';
import AttributeSelectModal from '@/pages/model/thing/components/detail/thingModel/components/AttributeSelectModal.vue';
import { to } from 'await-to-js';

const modelDetail = inject<any>('modelDetail')?.value;
const attributeTypeList = inject<any>('AttributeTypeList');
const tableRef = useTemplateRef<DataGridInstance>('table');

const queryData = ref({
    attributeName: '',
    attributeType: ''
});

const autoLoad = reactive<AutoLoadConfig>({
    debounce: true,
    reloadDeps: [queryData],
    onLoad: async (current, size) => {
        const res = await modelService.attribute.getList({
            current,
            size,
            objectName: modelDetail.objectName,
            ...queryData.value
        });
        return { data: res.data.records, total: res.data.total };
    }
});

function onNewItem() {
    showPopupBox(AttributeFormModal, {
        modelDetail,
        attributeTypeList: attributeTypeList.value,
        callback: tableRef.value?.refresh
    });
}

async function onDeleteItem(row: any) {
    const [err] = await to(
        ElMessageBox.confirm(
            row.attributeType !== 'CHILD_MODEL' && modelDetail.modifierType !== 'SINGLE'
                ? `父模型属性 ${row?.displayName} 删除后，所有添加该属性的对象模型内，都将一并删除，确认删除？`
                : `是否确认删除属性 ${row?.displayName} ？`,
            '提示',
            {
                confirmButtonText: '确认',
                cancelButtonText: '取消',
                type: 'warning'
            }
        )
    );
    if (!err) {
        modelService.attribute.del(row.id).then(tableRef.value?.refresh);
    }
}

function onRemoveItem(row: any) {
    modelService.attribute
        .removeExtends({
            objectName: modelDetail.objectName,
            attributeNames: [row.attributeName]
        })
        .then(tableRef.value?.refresh);
}

function onSelectFormParent() {
    showPopupBox(AttributeSelectModal, {
        modelDetail,
        callback: tableRef.value?.refresh,
        attributeTypeList: attributeTypeList.value
    });
}

function onEditItem(row: any) {
    showPopupBox(AttributeFormModal, {
        modelDetail,
        detail: row,
        attributeTypeList: attributeTypeList.value,
        callback: tableRef.value?.refresh
    });
}

function onViewItem(row: any) {
    showPopupBox(AttributeFormModal, {
        readOnly: true,
        modelDetail,
        detail: row,
        attributeTypeList: attributeTypeList.value,
        callback: tableRef.value?.refresh
    });
}
</script>
<style scoped lang="scss"></style>
